package com.github.cakin.shiro.chapter7.web.servlet;

import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @className: FormFilterLoginServlet
 * @description: 基于表单的拦截器身份验证
 * @date: 2020/5/21
 * @author: cakin
 */
@WebServlet(name = "formFilterLoginServlet", urlPatterns = "/formfilterlogin")
public class FormFilterLoginServlet extends HttpServlet {

    @Override
    protected void doGet( HttpServletRequest req, HttpServletResponse resp ) throws ServletException, IOException {
        doPost(req, resp);
    }

    /**
     * 功能描述：基于表单的拦截器身份验证
     *
     * @param req  请求
     * @param resp 响应
     * @throws ServletException
     * @throws IOException
     * 测试说明
     * 输入 http://localhost:8080/chapter7/role，会跳转到 “/formfilterlogin” 登录表单，提交表单如果登录成功，
     * 会直接重定向会之前的地址 “/role”；
     * 输入“http://localhost:8080/chapter7/formfilterlogin” ，登录成功将直接到默认的 successUrl。
     * @author cakin
     * @date 2020/5/21
     */
    @Override
    protected void doPost( HttpServletRequest req, HttpServletResponse resp ) throws ServletException, IOException {
        // 通过 shiroLoginFailure 得到 authc 登录失败时的异常类型名，然后根据此异常名来决定显示什么错误消息。
        String errorClassName = (String) req.getAttribute("shiroLoginFailure");

        if (UnknownAccountException.class.getName().equals(errorClassName)) {
            req.setAttribute("error", "用户名/密码错误");
        } else if (IncorrectCredentialsException.class.getName().equals(errorClassName)) {
            req.setAttribute("error", "用户名/密码错误");
        } else if (errorClassName != null) {
            req.setAttribute("error", "未知错误：" + errorClassName);
        }
        req.getRequestDispatcher("/WEB-INF/jsp/formfilterlogin.jsp").forward(req, resp);
    }
}
